package com.willie.elasticjob.service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import com.willie.elasticjob.dao.ElasticJobConfigDao;
import com.willie.elasticjob.dao.ElasticJobConfigLogDao;
import com.willie.elasticjob.entity.ElasticJobConfig;
import com.willie.elasticjob.entity.ElasticJobConfigLog;
import com.willie.elasticjob.runner.ElasticJobRunner;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * job service
 *
 * @author xing
 */
@Service
public class ElasticJobService {

    @Autowired
    private ElasticJobConfigDao elasticJobConfigDao;
    @Autowired
    private ElasticJobConfigLogDao elasticJobConfigLogDao;

    public long getElasticJobConfigCount(String jobName) {
        return elasticJobConfigDao.countElasticJobConfigByJobName(jobName);
    }

    public ElasticJobConfig insert(ElasticJobConfig config) {
        return elasticJobConfigDao.save(config);
    }

    /**
     * 更新
     *
     * @param config
     * @return
     */
    public ElasticJobConfig update(ElasticJobConfig config) {
        ElasticJobConfig bean = elasticJobConfigDao.save(config);

        if (bean == null) {
            backup(bean);
        }

        return bean;
    }

    public ElasticJobConfig getElasticJobConfigById(String id) {
        Optional<ElasticJobConfig> jobConfig = elasticJobConfigDao.findById(Long.valueOf(id));
        return jobConfig.orElse(null);
    }

    public void delete(String id) {
        ElasticJobConfig jobConfig = elasticJobConfigDao.findById(Long.valueOf(id)).orElse(null);
        backup(jobConfig);
        elasticJobConfigDao.delete(jobConfig);
    }

    public long getElasticJobConfigLogCount(String jobName) {
        return elasticJobConfigLogDao.countElasticJobConfigLogByJobName(jobName);
    }

    private void backup(ElasticJobConfig jobConfig) {
        ElasticJobConfigLog configLog = new ElasticJobConfigLog();
        BeanUtils.copyProperties(jobConfig, configLog);
        LocalDateTime time = LocalDateTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = time.atZone(zoneId).toInstant();
        configLog.setCreateTime(Date.from(instant));
        elasticJobConfigLogDao.save(configLog);
    }

}
